package ast;

import java.io.File;

import javax.swing.JFileChooser;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jface.viewers.IStructuredSelection;

import ast.io.statDataWriter;
import astStatData.ElementMap;
import astStatData.MapBuilder;
import astaction.ReferenceTracer;

public class ASTGenerater {
	private IStructuredSelection struSel;
	private boolean isExist;
	public ElementMap map; 
	
	public ASTGenerater(IStructuredSelection selection) throws JavaModelException{
		isExist = false;
		struSel = selection;
		map = new ElementMap();
		
		process();
		saveContext(map);
	}
	

    private void saveContext(ElementMap m) {
//    	JFileChooser chooser = new JFileChooser(".");
////     	int r = chooser.showSaveDialog(this);
////    	if (r != JFileChooser.APPROVE_OPTION) return;
    	File file = new File("C:/Users/ecinos/project/PlugInWS/RFcontextTEST.xml");
    	new statDataWriter().write(m, file);
	}
	
	public boolean isCUexist(){
		return isExist;
	}
	
	public void process() throws JavaModelException{
		Object elem = struSel.getFirstElement();
		if( elem instanceof IPackageFragment ){
			IPackageFragment pkg = (IPackageFragment) elem;
			ICompilationUnit[] ICUs = pkg.getCompilationUnits();
			for(int i=0; i<ICUs.length; i++){
				System.out.println("\""+ICUs[i].getElementName()+"\"");
				buildMap( getCU(ICUs[i]) );
			}
			for(int i=0; i<ICUs.length; i++){
				System.out.println("\n\""+ICUs[i].getElementName()+"\"");
				referenceTrace( getCU(ICUs[i]) );
			}
			isExist = true;
		}else if(elem instanceof ICompilationUnit){
			ICompilationUnit ICU = (ICompilationUnit) elem;
			buildMap( getCU(ICU) );
			referenceTrace( getCU(ICU) );
			
			
			
			isExist = true;
		}else{
			isExist = false;
		}
	}
	
	/*
	public void playAdaptor(ICompilationUnit icu){
		  IAdaptable a = new IJavaElement();;
		  ICompilationUnit icu2 = (ICompilationUnit) a.getAdapter(icu.getClass());
		  
	}
	*/
	
	public void buildMap(CompilationUnit cu){		
		System.out.println(cu.toString());
	    MapBuilder mb = new MapBuilder(map, cu);
		cu.accept(mb);
//		ASTTracer tracer = new ASTTracer(map);
//		cu.accept(tracer);
		
	}
	
	private void referenceTrace(CompilationUnit cu){
		ReferenceTracer refTracer = new ReferenceTracer(map);
		cu.accept(refTracer);
	}
	
	private CompilationUnit getCU(ICompilationUnit icu){
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setResolveBindings(true);
		parser.setSource(icu);
		CompilationUnit cu = (CompilationUnit) parser.createAST(null);
		return cu;
	}
	
}
